<template>
  <el-container class="course-detail-container">
    <el-main class="course-main">
      <el-card class="course-info-card mb-4">
        <template #header>
          <div class="card-header-title">
            {{ courseStore.chooseCourse.title }}
          </div>
        </template>
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="cover-image-wrapper">
              <img
                :src="courseStore.chooseCourse.coverUrl"
                alt="Course Cover"
                class="course-cover-image"
              />
              <el-button
                type="primary"
                :icon="Edit"
                circle
                class="edit-cover-button"
                @click="openUploadDialog"
              ></el-button>
            </div>
          </el-col>

          <el-col :span="16">
            <p class="course-description">
              {{ courseStore.chooseCourse.description }}
            </p>
            <el-col :span="8">
              <el-rate
                :model-value="courseStore.chooseCourse.star"
                disabled
                show-score
                text-color="#ff9900"
                score-template="{value}分"
              ></el-rate>
            </el-col>
            <el-divider></el-divider>
            <el-row>
              <el-col :span="12">
                <p>
                  <strong>分类:</strong>
                  {{ courseStore.chooseCourse.categoryName }}
                </p>
                <p>
                  <strong>难度:</strong>
                  {{ courseStore.chooseCourse.difficulty }}
                </p>
              </el-col>

              <el-col :span="12">
                <p>
                  <strong>时长:</strong>
                  {{ courseStore.chooseCourse.lastingTime }} 分钟
                </p>
                <p>
                  <strong>创建者:</strong>
                  {{ courseStore.chooseCourse.createdBy }}
                </p>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
      </el-card>

      <el-card class="course-resources-card mb-4">
        <template #header>
          <div class="card-header-title">课程资源</div>
        </template>
        <el-row :gutter="20">
          <el-col
            :xs="24"
            :sm="12"
            :md="6"
            v-for="resource in courseStore.courseResources"
            :key="resource.id"
          >
            <el-card shadow="hover" class="resource-item">
              <div class="resource-icon">
                <i
                  v-if="resource.type === 'video'"
                  class="bi bi-play-circle-fill"
                ></i>
                <i
                  v-else-if="resource.type === 'document'"
                  class="bi bi-file-earmark-text-fill"
                ></i>
              </div>
              <div class="resource-content">
                <h6 class="resource-name">{{ resource.resourceName }}</h6>
                <p class="resource-type text-muted">
                  {{ resource.type === "video" ? "视频" : "文档" }}
                </p>
                <!-- <el-button
                  type="primary"
                  link
                  @click="watchOnline(resource, resource.url, resource.type,courseStore.chooseCourse.id)"
                  >查看资源
                </el-button> -->
              </div>
            </el-card>
          </el-col>
        </el-row>
      </el-card>

      <el-card class="course-qa-card">
        <template #header>
          <div class="card-header-title">问答区</div>
        </template>
        <div class="qa-section">
          <div class="qa-list">
            <div
              v-for="(qa, index) in qaList"
              :key="qa.id || index"
              class="qa-item"
            >
              <p><strong>Q:</strong> {{ qa.questions.content }}</p>
              <p v-for="ans in qa.answers">
                <strong>A:</strong> {{ ans.content || "暂无回答" }}
              </p>

              <!-- 教师可以回答问题 -->
              <div v-if="isTeacher && !qa.answer" class="answer-form mt-2">
                <el-input
                  type="textarea"
                  :rows="2"
                  placeholder="输入回答..."
                  v-model="qa.tempAnswer"
                  class="mb-2"
                ></el-input>
                <el-button
                  type="success"
                  size="small"
                  @click="answerQuestion(qa.questions.id, qa.tempAnswer)"
                >
                  提交回答
                </el-button>
              </div>
              <el-divider></el-divider>
            </div>
            <div ref="qaEnd"></div>
          </div>
          <el-input
            type="textarea"
            :rows="3"
            placeholder="提出你的问题..."
            v-model="newQuestion"
            class="mb-2"
          ></el-input>
          <el-button type="primary" @click="submitQuestion"
            >提交问题
          </el-button>
        </div>
      </el-card>
    </el-main>
  </el-container>
</template>

<script setup>
import { ref, onMounted, computed, nextTick } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useCourseStore } from "@/stores/course.js";
import UploadCoverDialog from "@/components/common/UploadCoverDialog.vue";
import { Edit } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import common_util from "@/util/common_util.js";
import { useUserStore } from "@/stores/user.js";

const userStore = useUserStore();
const route = useRoute();
const router = useRouter();
const courseStore = useCourseStore();

const courseResources = ref([]);
const myNotes = ref("");
const newQuestion = ref("");
const qaList = computed(() => courseStore.questions || []);
// 获取当前用户ID和角色信息
const userId = computed(() => userStore.user?.id);
const isTeacher = computed(() => userStore.isTeacher);
const isStudent = computed(() => userStore.isStudent);
const courseId = route.params.id;
onMounted(async () => {
  const courseId = route.params.id;
  if (courseId) {
    courseStore.getCourseDetail(courseId);
    courseStore.getQuestionAndAnswers(userId.value, courseId);
  }
});

const submitQuestion = async () => {
  if (!newQuestion.value.trim()) {
    ElMessage.warning("问题内容不能为空！");
    return;
  }

  if (!userId.value || !courseId) {
    ElMessage.warning("用户信息或课程信息不完整，无法提交问题");
    return;
  }

  try {
    // 使用common_util提交问题
    const content = newQuestion.value;
    await new Promise((resolve, reject) => {
      common_util.post(
        "/api/study/ask",
        {
          userId: userId.value,
          courseId: courseId,
          content: content,
        },
        {},
        (data) => {
          ElMessage.success("问题提交成功");
          resolve(data);
        },
        (message) => {
          ElMessage.error(`提交问题失败: ${message}`);
          reject(message);
        },
      );
    });

    // 清空输入框
    newQuestion.value = "";

    // 重新获取问题列表
    await courseStore.getQuestionAndAnswers(userId.value, courseId);

    nextTick(() => {
      qaEnd.value?.scrollIntoView({ behavior: "smooth" });
    });
  } catch (error) {
    console.error("提交问题失败:", error);
    ElMessage.error("提交问题失败，请稍后重试");
  }
};

// 教师回答问题
const answerQuestion = async (questionId, answerContent) => {
  if (!isTeacher.value) {
    ElMessage.warning("只有教师可以回答问题");
    return;
  }

  if (!answerContent || !answerContent.trim()) {
    ElMessage.warning("回答内容不能为空");
    return;
  }

  try {
    await courseStore.answerQuestion(answerContent, userId.value, questionId);

    // 重新获取问题列表
    await courseStore.getQuestionAndAnswers(userId.value, courseId);
  } catch (error) {
    console.error("回答问题失败:", error);
    ElMessage.error("回答问题失败，请稍后重试");
  }
};
const uploadDialogRef = ref(null);

const openUploadDialog = () => {
  uploadDialogRef.value.open(course.value.coverUrl);
};

const handleCoverUploadSuccess = (newUrl) => {
  course.value.coverUrl = newUrl;
  // 这里可以添加调用后端接口更新课程封面的逻辑
  console.log("New cover URL:", newUrl);
};

const openResource = (url) => {
  window.open(url, "_blank");
};

const watchOnline = (resource, url, type) => {
  courseStore.chooseResource = resource;
  console.log("resource", resource.id);
  console.log("courseId", courseId);
  if (type === "video") {
    router.push({
      path: "/learning",
      query: { url: url, courseId: courseId , resourceId: resource.id},
    });
  } else {
    router.push({
      path: "/learning/document",
      query: { url: url, courseId: courseId , resourceId: resource.id},
    });
  }
};
</script>

<style scoped>
.course-detail-container {
  padding: 20px;
  background-color: #f0f2f5;
}

.course-main {
  max-width: 1200px;
  margin: 0 auto;
}

.course-info-card .card-header-title,
.course-resources-card .card-header-title,
.course-notes-card .card-header-title,
.course-qa-card .card-header-title {
  font-size: 20px;
  font-weight: bold;
  color: #333;
}

.cover-image-wrapper {
  position: relative;
  width: 100%;
  height: 200px;
}

.course-cover-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 8px;
}

.edit-cover-button {
  position: absolute;
  bottom: 10px;
  right: 10px;
}

.course-description {
  font-size: 16px;
  line-height: 1.6;
  color: #555;
}

.resource-item {
  display: flex;
  align-items: center;
  padding: 15px;
  margin-bottom: 15px;
}

.resource-icon {
  font-size: 40px;
  color: #409eff;
  margin-right: 15px;
}

.resource-content {
  flex-grow: 1;
}

.resource-name {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 5px;
}

.resource-type {
  font-size: 14px;
}

.qa-section {
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}
</style>
